package com.ruoyi.web.controller.mop.prescription;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.mop.domain.Category;
import com.ruoyi.mop.domain.Medicine;
import com.ruoyi.mop.domain.Mop;
import com.ruoyi.mop.service.ICategoryService;
import com.ruoyi.mop.service.IMedicineService;
import com.ruoyi.mop.service.IMopService;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.users.domain.Patient;
import com.ruoyi.users.service.IPatientService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.mop.domain.Prescription;
import com.ruoyi.mop.service.IPrescriptionService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 处方Controller
 *
 * @author ruoyi
 * @date 2024-03-08
 */
@RestController
@RequestMapping("/mop/prescription")
public class PrescriptionController extends BaseController
{
    @Autowired
    private IPrescriptionService prescriptionService;
    @Autowired
    private IPatientService patientService;
    @Autowired
    private ISysUserService userService;
    @Autowired
    private IMopService mopService;
    @Autowired
    private IMedicineService medicineService;
    @Autowired
    private ICategoryService categoryService;

    /**
     * 查询处方列表
     */
    @PreAuthorize("@ss.hasPermi('mop:prescription:list')")
    @GetMapping("/list")
    public TableDataInfo list(Prescription prescription)
    {
        startPage();
        List<Prescription> list = prescriptionService.selectPrescriptionList(prescription);
        return getDataTable(list);
    }

    /**
     * 获取处方药品列表
     */
    @PreAuthorize("@ss.hasPermi('mop:prescription:getMopList')")
    @GetMapping("/getMopList")
    public AjaxResult getMopList(Long id)
    {
        Mop mop = new Mop();
        mop.setPrescriptionId(id);
        List<Mop> mopList = mopService.selectMopList(mop);
        //添加medicineName、image、amount字段,更新price字段
        if (mopList != null && mopList.size() > 0){
            mopList = mopList.stream().peek(item->{
                Medicine medicine = medicineService.selectMedicineById(item.getMedicineId());
                System.err.println(medicine);
                item.setMedicineName(medicine.getName());
                item.setMedicineImg(medicine.getImage());
                item.setAmount(item.getPrice() * item.getNumber());
            }).collect(Collectors.toList());
        }
        return AjaxResult.success(mopList);
    }

    /**
     * 获取所有药品列表
     */
    @PostMapping("/listComs")
    public AjaxResult listComs()
    {
        List<Category> categoryList = categoryService.selectCategoryList(null);
        //添加MedicineList字段
        categoryList = categoryList.stream().peek(item->{
            Medicine medicine = new Medicine();
            medicine.setCategoryId(item.getId());
            List<Medicine> medicineList = medicineService.selectMedicineList(medicine);
            item.setMedicineList(medicineList);
        }).collect(Collectors.toList());
        return AjaxResult.success(categoryList);
    }

    /**
     * 添加药品到 mop表
     */
    @PostMapping("/addMops")
    public AjaxResult addMops(@RequestBody List<Medicine> medicineList,@RequestParam Long pid)
    {
        for (Medicine medicine : medicineList) {
            Mop mop = new Mop();
            mop.setPrescriptionId(pid);
            mop.setMedicineId(medicine.getId());

            mop.setPrice(medicine.getPrice());
            mop.setNumber(medicine.getNumber());
            mop.setRemark(medicine.getRemark());
            mop.setAmount(medicine.getNumber()*medicine.getPrice());
            mopService.insertMop(mop);
        }
//        List<Mop> mopList = medicineList.stream().map(item -> {
//            Mop mop = new Mop();
//            mop.setPrescriptionId(pid);
//            mop.setMedicineId(item.getId());
//            mop.setPrice(item.getPrice());
//            mop.setNumber(item.getNumber());
//            mop.setRemark(item.getRemark());
//            return mop;
//        }).collect(Collectors.toList());
//        mopService.batchInsertMopList(mopList);
        Mop mop = new Mop();
        mop.setPrescriptionId(pid);
        List<Mop> list = mopService.selectMopList(mop);
        list = list.stream().peek(item->{
            Medicine medicine = medicineService.selectMedicineById(item.getMedicineId());
            item.setMedicineName(medicine.getName());
            item.setMedicineImg(medicine.getImage());
            item.setAmount(item.getNumber()*medicine.getPrice());
        }).collect(Collectors.toList());
        return AjaxResult.success(list);
    }

    /**
     * 导出处方列表
     */
    @PreAuthorize("@ss.hasPermi('mop:prescription:export')")
    @Log(title = "处方", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Prescription prescription)
    {
        List<Prescription> list = prescriptionService.selectPrescriptionList(prescription);
        ExcelUtil<Prescription> util = new ExcelUtil<Prescription>(Prescription.class);
        util.exportExcel(response, list, "处方数据");
    }

    /**
     * 获取处方详细信息
     */
    @PreAuthorize("@ss.hasPermi('mop:prescription:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(prescriptionService.selectPrescriptionById(id));
    }

    /**
     * 新增处方
     */
    @PreAuthorize("@ss.hasPermi('mop:prescription:add')")
    @Log(title = "处方", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Prescription prescription)
    {
        SysUser patient = userService.checkPatientAndDoctor(prescription.getPatientName(), prescription.getIdNumber(), null, null);
        if (patient == null) {
            return AjaxResult.error("患者姓名或身份证号输入错误");
        }
        if (!"11".equals(patient.getUserType())) {
            return AjaxResult.error("该用户不属于患者用户");
        }
        SysUser doctor = userService.checkPatientAndDoctor(null, null, prescription.getDoctorName(), prescription.getDoctorId());
        if (doctor == null) {
            return AjaxResult.error("医生姓名或工号输入错误");
        }
        if (!"00".equals(doctor.getUserType()) || "admin".equals(doctor.getUserName())) {
            return AjaxResult.error("该用户不属于医生用户");
        }
        return toAjax(prescriptionService.insertPrescription(prescription));
    }

    /**
     * 修改处方
     */
    @PreAuthorize("@ss.hasPermi('mop:prescription:edit')")
    @Log(title = "处方", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Prescription prescription)
    {
        SysUser patient = userService.checkPatientAndDoctor(prescription.getPatientName(), prescription.getIdNumber(), null, null);
        if (patient == null) {
            return AjaxResult.error("患者姓名或身份证号输入错误");
        }
        if (!"11".equals(patient.getUserType())) {
            return AjaxResult.error("该用户不属于患者用户");
        }
        SysUser doctor = userService.checkPatientAndDoctor(null, null, prescription.getDoctorName(), prescription.getDoctorId());
        if (doctor == null) {
            return AjaxResult.error("医生姓名或工号输入错误");
        }
        if (!"00".equals(doctor.getUserType()) || "admin".equals(doctor.getUserName())) {
            return AjaxResult.error("该用户不属于医生用户");
        }
        return toAjax(prescriptionService.updatePrescription(prescription));
    }

    /**
     * 删除处方
     */
    @PreAuthorize("@ss.hasPermi('mop:prescription:remove')")
    @Log(title = "处方", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(prescriptionService.deletePrescriptionByIds(ids));
    }

    /**
     * 删除处方药品关联的数据
     */
    @PreAuthorize("@ss.hasPermi('mop:prescription:delMop')")
    @DeleteMapping("/delMop/{ids}")
    public AjaxResult delMop(@PathVariable Long[] ids)
    {
        return toAjax(mopService.deleteMopByIds(ids));
    }

}
